package encodeDecode;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import protocol.Header;
import protocol.IOMessage;

public class IOMessageDecoder extends LengthFieldBasedFrameDecoder{
	
	
	public IOMessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) throws IOException{
		// TODO Auto-generated constructor stub
	    super(maxFrameLength, lengthFieldOffset, lengthFieldLength);
	}
	
	@Override
	protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
		// TODO Auto-generated method stub
		
		System.out.println("IO decode message--" + in.capacity() + " -- > " + in.toString());
		
		ByteBuf frame = (ByteBuf)super.decode(ctx, in);
		if(frame == null){return null;}
		
		int length = frame.readInt();
		byte[] bytes = new byte[length];
        frame.readBytes(bytes);
		String getMes = new String(bytes);
		
		IOMessage mes = (IOMessage)JSON.parseObject(getMes, IOMessage.class);
		
		if(mes == null)System.out.println("decode == null ");
		else System.out.println("IO decode complete --> " + mes );
		
		return mes;
	}
}
